package com.itheima.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.SetmealMapper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Setmeal;
import com.itheima.utils.JedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    JedisUtil jedisUtil;
    @Autowired
    SetmealMapper setmealMapper;

    @Override
    public void add(Setmeal setmeal) {
        // 保存套餐基本信息并返回主键
        setmealMapper.add(setmeal);
        // 批量建立关系
        Integer setmealId = setmeal.getId();
        List<Integer> checkgroupIds = setmeal.getCheckgroupIds();
        //insert into 表名（字段1 字段2） values(1,2) ,(1,3),(1,4)

        if (CollectionUtil.isNotEmpty(checkgroupIds)) {
            setmealMapper.setSetmealAndCheckGroupBatch(setmealId, checkgroupIds);
        }

    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Page page = PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());

        setmealMapper.findPage(queryPageBean.getQueryString());

        return new PageResult(page.getTotal(), page.getResult());
    }

    //rides 缓存  setmealMapper.getSetmeal();
    @Override
    public JSONArray getSetmeal() throws Exception {
//判断套餐列表是否在缓存中，没有就到数据查，并存放到缓存中；
        String setmealList = jedisUtil.get("SetmealList");
        if (null == setmealList) {
            List<Setmeal> setmeal = setmealMapper.getSetmeal();
            setmealList = new ObjectMapper().writeValueAsString(setmeal);
            jedisUtil.add("SetmealList", 60 * 60 * 24, setmealList); //一天自动清一次缓冲
        }
        JSONArray array = JSONUtil.parseArray(setmealList);

        return array;
    }


    @Override
    public Setmeal findById(Integer id) {
        //根据套餐id查询套餐详情
        Setmeal setmeal = setmealMapper.findById(id);
        if (null != setmeal) {
            //根据套餐id查询套餐下面所有检查组
            List<CheckGroup> checkGroups = setmealMapper.findCheckGroupBySetmealId(id);
            if (CollectionUtil.isNotEmpty(checkGroups)) {
                for (CheckGroup checkGroup : checkGroups) {
                    //循环检查组查询下面的检查项
                    List<CheckItem> checkItems = setmealMapper.findCheckItemByCheckGroupId(checkGroup.getId());
                    checkGroup.setCheckItems(checkItems);
                }
            }
            setmeal.setCheckGroups(checkGroups);
        }
        return setmeal;
    }

    //套餐详情缓存
    @Override
    public JSONObject findByIdBatch(Integer id) throws Exception {
        String setmealDetail = jedisUtil.get("Setmeal" + id);
        //判断Redis是否有数据
        if (null == setmealDetail) {
            //根据套餐id查询套餐详情
            Setmeal setmeal = setmealMapper.findById(id);
            if (null != setmeal) {
                //根据套餐id查询套餐下面所有检查组
                List<CheckGroup> checkGroups = setmealMapper.findCheckGroupBySetmealId(id);
                if (CollectionUtil.isNotEmpty(checkGroups)) {
                    List<Integer> ids = new ArrayList<>();
                    for (CheckGroup checkGroup : checkGroups) {
                        ids.add(checkGroup.getId());
                    }
                    List<CheckItem> checkItems = setmealMapper.findCheckItemByCheckGroupIdBatch(ids);
                    //手动分组
                    Map<Integer, List<CheckItem>> map = new HashMap<>();
                    map = checkItems.stream().collect(Collectors.groupingBy(CheckItem::getCheckGroupId));
                    for (CheckGroup checkGroup : checkGroups) {
                        checkGroup.setCheckItems(map.get(checkGroup.getId()));
                    }
                }
                setmeal.setCheckGroups(checkGroups);
            }
            setmealDetail = new ObjectMapper().writeValueAsString(setmeal);
            jedisUtil.add("Setmeal"+id, 60 * 60 * 24, setmealDetail); //一天自动清一次缓冲
        }
        JSONObject setmeal = JSONUtil.parseObj(setmealDetail);
        return setmeal;
    }

    @Override
    public Setmeal findDetailById(Integer id) {
        return setmealMapper.findById(id);
    }
}
